﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace Ignitron.EEngine.Adapters.OpenGL
{
    /// <summary>
    /// Internal class representing a class for rendering OpenTK background
    /// </summary>
    internal class OpenTKBackground
    {
        private IBackground mBackground;

        /// <summary>
        /// Constructor
        /// </summary>
        public OpenTKBackground(IBackground background)
        {
            mBackground = background;
        }

        /// <summary>
        /// Rendering method
        /// </summary>
        public void Render(int w, int h, int bufferId, float z, bool isLightingEnabled)
        {
            // SET UP VIEWPORT
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, bufferId);
            GL.Disable(EnableCap.Lighting);
            GL.MatrixMode(MatrixMode.Projection);
            GL.PushMatrix();
            GL.LoadIdentity();
            int sizeB = Math.Min(w, h);
            GL.Ortho(0, w, 0, h, -1, 1);
            GL.Viewport(0, 0, w, h);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.PushMatrix();
            GL.LoadIdentity();
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // RENDER
            int texID;
            GL.GenTextures(1, out texID);
            GL.BindTexture(TextureTarget.Texture2D, texID);
            GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Replace);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Nearest);
            GL.TexImage2D<byte>(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, mBackground.Width, mBackground.Height, 0, PixelFormat.Rgb, PixelType.UnsignedByte, mBackground.Pixels);

            GL.Begin(PrimitiveType.Quads);

            GL.TexCoord2(0, 0);
            GL.Vertex3(0, 0, z);
            GL.TexCoord2(1, 0);
            GL.Vertex3(w, 0, z);
            GL.TexCoord2(1, 1);
            GL.Vertex3(w, h, z);
            GL.TexCoord2(0, 1);
            GL.Vertex3(0, h, z);

            GL.End();
            GL.DeleteTexture(texID);

            // RESTORE VIEWPORT
            GL.MatrixMode(MatrixMode.Projection);
            GL.PopMatrix();
            GL.Viewport(0, 0, w, h); // Use all of the glControl painting area

            GL.MatrixMode(MatrixMode.Modelview);
            GL.PopMatrix();

            if (isLightingEnabled)
                GL.Enable(EnableCap.Lighting);
        }
    }
}
